import Tools from '../../util/tools'

let storeAPI = function(Wine){

	/**
	 * [$get 从内部_store对象获取数据]
	 * @param  {[String]} expression [结构化表达式]
	 * @return {[type]}            [description]
	 */
	Wine.prototype.$get = function(expression){
		let attrNodes = expression.split('.');
		let lh = attrNodes.length;
		if (lh > 0) {
			let node = attrNodes[0];
			let i = 0;
			let store = this._store;
			while(node){
				i++
				store = store[node];
				node = attrNodes[i];
			}
			return store;
		}
	}

	/**
	 * [$set 向内部_store设置新的数据]
	 * @param {[type]} expression [格式化表达式]
	 * @param {[type]} value      [description]
	 */
	Wine.prototype.$set = function(expression,value){
		let attrNodes = expression.split('.');
		let lh = attrNodes.length;
		if (lh > 0) {
			let i = 0;
			let node = attrNodes[i];
			let store = this._store;
			if (lh !== 1) {
				while(node){
					i++
					store = store[node];
					node = attrNodes[i];
					if (i > (lh - 2)) {
						break;
					}
				}
			}
			switch(Tools.toType(store)){
				case '[object Object]':
					store[node] = value;
					break;
				case '[object Array]':
					store[Tools.exportToNumber(node)] = value;
					break;
				default:
					store = value;
					break;
			}
		}
	}

	/**
	 * [$filter 对_store数据进行筛选]
	 * @param  {[type]} expression [description]
	 * @param  {[type]} value      [description]
	 * @return {[type]}            [description]
	 */
	Wine.prototype.$filter = function(expression,value){
		let data = this.$get(expression)
		let result = []
		if (Tools.toType(data) === '[object Array]') {
			let i = data.length;
			if (Tools.isPlainObject(value)) {
				value = JSON.stringify(value);
			}
			result = data.filter(function(val,i){
				let n;
				switch(Tools.toType(value)){
					case '[object Object]':
						n = (JSON.stringify(val) === value)
						break
					case '[object Function]':
						n = value(val,i)
						break
					default:
						n = (val === value)
						break
				}
				return n
			})
		}
		return result
	}

	/**
	 * [$sort 对_store的数据进行排序]
	 * @param  {[type]} expression [description]
	 * @param  {[type]} value      [description]
	 * @return {[type]}            [description]
	 */
	Wine.prototype.$sort = function(expression,value){

	}

	/**
	 * [$remove 从_store数据中删除数据]
	 * @param  {[type]} expression [description]
	 * @return {[type]}            [description]
	 */
	Wine.prototype.$remove = function(expression){

	}

}
module.exports = storeAPI